package com.atguigu.java.ai.langchain4j.store;

import com.atguigu.java.ai.langchain4j.bean.ChatMessages;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @Author: 🐱🐱🐱
 * @Date: 2025/9/1 20:09
 * @Description:
 **/
@Component
public class MongoChatMemoryStore implements ChatMemoryStore {

    @Resource
    private MongoTemplate mongoTemplate;
    //接受消息
    @Override
    public List<ChatMessage> getMessages(Object messageId) {
        //1.构造查询条件 根据消息id查询
        Query query = new Query();
        query.addCriteria(Criteria.where("messageId").is(messageId));
        //2.调用mongoTemplate查询
       ChatMessages chatMessages = mongoTemplate.findOne(query, ChatMessages.class);
        //3.查不到 返回空的集合
        if(chatMessages == null){
            return Collections.emptyList();
        }
        //4.能查到 获取消息内容 将消息内容在转成一个集合
        List<ChatMessage> chatMessageList = ChatMessageDeserializer.messagesFromJson(chatMessages.getContent());
        //返回数量
        return chatMessageList;
    }

    //修改消息
    @Override
    public void updateMessages(Object messageId, List<ChatMessage> messages) {
        Query query = new Query();
        query.addCriteria(Criteria.where("messageId").is(messageId));

        Update update = new Update();
        update.set("content",ChatMessageSerializer.messagesToJson(messages));

        mongoTemplate.upsert(query,update, ChatMessages.class);
    }
    //删除消息
    @Override
    public void deleteMessages(Object messageId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("messageId").is(messageId));
      //调用mongoTemplate删除
        mongoTemplate.remove(query, ChatMessages.class);
    }
}
